//
//  WXLMoreMusicViewController.m
//  段子手
//
//  Created by dllo on 16/3/21.
//  Copyright © 2016年 JokesTeam. All rights reserved.
//

#import "WXLMoreMusicViewController.h"

const CGFloat GroupHeight = 200;

@interface WXLMoreMusicViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, WXLHotSongsTableViewCellDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIImageView *imagView; /**< 大图 */
//@property (nonatomic, retain) UILabel *titleLabel; /**< VC标题label */
@property (nonatomic, retain) NSMutableArray *songsArr; /**< 歌单数组 */

@property (nonatomic, strong) UIVisualEffectView *visualEfView; /**< 毛玻璃 */
@property (nonatomic, retain) UIImageView *imgView; /**< 播放旋转小图 */
@property (nonatomic, retain) TouchMoveView *touchMovieView;
@property (nonatomic, retain) UIButton *refreshButton; /**< 刷新按钮 */
@property (nonatomic, retain) UIButton *playButton; /**< 播放按钮 */

@property (nonatomic, retain) CABasicAnimation *animation; /**< 动画 */
@property (nonatomic, retain) UIButton *button; /**< 旋转上的小button */

@property (nonatomic, assign) BOOL isPlay;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, assign) BOOL isFirst; /**< 是否刚进入该页面 */
@property (nonatomic, assign) NSInteger page;

@end

@implementation WXLMoreMusicViewController



- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.songsArr = [NSMutableArray new];
        self.arr = [NSMutableArray new];
        self.isPlay = YES;
        self.isFirst = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"beijing.jpg"]];
    
    // 毛玻璃
    [self createVisualEfView];
    
    [self createSubView];
    
    //
    [self dataHandelFromUrl];
}



- (void)createSubView {
    
    // 创建返回item
    [self createLeftItem];
    
    // 创建tableView
    [self createTableView];
    
    // 创建tableView头视图
    [self createTableViewHearder];
    
    // 创建可拖动的view
    [self createTouchMoveView];
    
    // 去除黑色素线条
    [self cancelBlackLine];
}

- (void)createAnimationView {
    
    self.imgView = [[UIImageView alloc] init];
    _imgView.frame = CGRectMake(_touchMovieView.frame.size.width / 2 - (_touchMovieView.frame.size.height - 10) / 2, 5, _touchMovieView.frame.size.height - 10, _touchMovieView.frame.size.height - 10);
    [self.touchMovieView addSubview:_imgView];
    _imgView.layer.cornerRadius = _imgView.frame.size.height / 2;
    _imgView.layer.masksToBounds = YES;
    _imgView.userInteractionEnabled = YES;
    
    self.refreshButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self.touchMovieView addSubview:_refreshButton];
    _refreshButton.frame = CGRectMake(_imgView.frame.origin.x - 90, 15, _imgView.frame.size.height - 20, _imgView.frame.size.height - 20);
    [_refreshButton setBackgroundImage:[UIImage imageNamed:@"iconfont-cainixihuan"] forState:(UIControlStateNormal)];
    [_refreshButton addTarget:self action:@selector(refreshButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.playButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self.touchMovieView addSubview:_playButton];
    _playButton.frame = CGRectMake(_imgView.frame.origin.x + _imgView.frame.size.width + 50, 15, _imgView.frame.size.height - 20, _imgView.frame.size.height - 20);
    [_playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-huiding"] forState:(UIControlStateNormal)];
    [_playButton addTarget:self action:@selector(playButtonButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self.imgView addSubview:_button];
    _button.frame = CGRectMake((_imgView.frame.size.width - 20) / 2, (_imgView.frame.size.height - 20) / 2, 20, 20);
    _button.layer.cornerRadius = 10;
    _button.layer.masksToBounds = YES;
    _button.backgroundColor = [UIColor whiteColor];
    [_button setTitleColor:[UIColor blackColor]forState:(UIControlStateNormal)];
    [_button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
  
    if (_myModel.picUrl.length) {
        [_imgView HANDLEIMAGE(_myModel.picUrl)];
        [_imagView HANDLEIMAGE(_myModel.picUrl)];
        [_button setTitle:@"播" forState:(UIControlStateNormal)];
    } else {
        _imgView.image = [UIImage imageNamed:@"beijing.jpg"];
        [_button setTitle:@"" forState:(UIControlStateNormal)];
    }
    
    // 保证安全
    if (!self.animation) {
        // CALayer 动画
        // Core Animtion
        self.animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    }
    // 旋转的起始值
    _animation.fromValue = [NSNumber numberWithFloat:0];
    // 旋转的结束值
    // π 是 180°  2π 是 360°
    _animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    // 重复次数
    _animation.repeatCount = NSIntegerMax;
    // 时间
    _animation.duration = 5;
    // 是否自动回到原来位置
    _animation.autoreverses = NO;
    // 是否按照结束位置继续旋转
    _animation.cumulative = YES;
    
    [_imgView.layer addAnimation:_animation forKey:@"标记"];
    
}

/** 创建可拖动的view */
- (void)createTouchMoveView {
    
    self.touchMovieView = [[TouchMoveView alloc] initWithFrame:CGRectMake(VIEW_CENTER_X - (kUIScreenWidth) / 2, kUIScreenHeight - 60, kUIScreenWidth, 60)];
    [self.view addSubview:_touchMovieView];
    _touchMovieView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"wxl"]];
    
    // touch上的毛玻璃
//    [self createVisualViewForTouch];
    // 动图
    [self createAnimationView];
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
    // 设置轻扫方向
    swipe.direction = UISwipeGestureRecognizerDirectionUp | UISwipeGestureRecognizerDirectionDown;
    [_touchMovieView addGestureRecognizer:swipe];
}

/** touch上的毛玻璃 */
- (void)createVisualViewForTouch {
    // 毛玻璃
    UIVisualEffectView *visualEfV = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visualEfV.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    visualEfV.alpha = 1;
    visualEfV.userInteractionEnabled = YES;
    
    [self.touchMovieView addSubview:visualEfV];
}

/** 毛玻璃 */
- (void)createVisualEfView {
    // 毛玻璃
    self.visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    _visualEfView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    _visualEfView.alpha = 1;
    _visualEfView.userInteractionEnabled = YES;
    
    [self.view addSubview:_visualEfView];
    
}

/** 创建返回item */
- (void)createLeftItem {
    UIBarButtonItem *leftReturnItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"iconfont-fanhui-4"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftReturnItemAction:)];
    self.navigationItem.leftBarButtonItem = leftReturnItem;
}

/** 创建tableView */
- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth - 0, kUIScreenHeight - 64) style:(UITableViewStylePlain)];
    [self.view addSubview:_tableView];
    _tableView.contentInset = UIEdgeInsetsMake(GroupHeight, 0, 0, 0);
    _tableView.showsVerticalScrollIndicator = NO;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _tableView.backgroundColor = [UIColor clearColor];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [_tableView registerClass:[WXLHotSongsTableViewCell class] forCellReuseIdentifier:@"WXLHotSongsTableViewCell"];
}

- (void)createTableViewHearder {
    // 设置大的图片
    self.imagView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -GroupHeight, self.view.frame.size.width, GroupHeight)];
    [self.tableView addSubview:_imagView];
    _imagView.image = [UIImage imageNamed:@"beijing.jpg"];
}




#pragma mark - tableView Delegate & DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _songsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WXLHotSongsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WXLHotSongsTableViewCell"];
    cell.backgroundColor = [UIColor clearColor];
    cell.model = _songsArr[indexPath.row];
    cell.delegate = self;
    cell.indexPath = indexPath;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    [PLAYMUSIC playMusicWithAvUrl:_songsArr dex:indexPath.row];
   
    [PLAYMUSIC startPlay];
    
    [_button setTitle:@"播" forState:(UIControlStateNormal)];
    
     WXLSongsModel *model = _songsArr[indexPath.row];
    [_imgView HANDLEIMAGE(model.picUrl)];
    [_imagView HANDLEIMAGE(model.picUrl)];
}



#pragma mark - WXLHotSongsTableViewCellDelegate
- (void)mVButtonAtionClick:(WXLSongsModel *)songsModel {
    
    WXLPLAYVIDEO.songsModel = songsModel;
    
    _isPlay = NO;
    [PLAYMUSIC pausePlay];
    
    [self presentViewController:WXLPLAYVIDEO animated:YES completion:nil];
    
}


#pragma mark - 数据请求 与 处理
- (void)dataHandelFromUrl {
    
    //  http://api.favorite.ttpod.com/favorite/song/plaza?address=辽宁省大连市沙河口区五一路314&agent=none&longitude=0.0&utdid=VGGJcU4veJsDACPAEYL62k1V&net=2&from=android&os=6.0.1&v=v8.4.0.2016022715&alf=700159&api_version=1.0&imei=863360026086235&version=405144&latitude=0.0&f=168&resolution=1080x1920&language=zh&random=1&user_id=0
    
    NSString *urlStr = [NSString stringWithFormat:@"http://api.favorite.ttpod.com/favorite/song/plaza?address=辽宁省大连市沙河口区五一路314&agent=none&longitude=0.0&utdid=VGGJcU4veJsDACPAEYL62k1V&net=2&from=android&os=6.0.1&v=v8.4.0.2016022715&alf=700159&api_version=1.0&imei=863360026086235&latitude=0.0&f=168&resolution=1080x1920&language=zh&random=0&user_id=0"];
    [WxlAPPTools GETWithURL:urlStr par:nil success:^(id responseObject) {
        
        if (_songsArr.count) {
            [self.songsArr removeAllObjects];
        }
        
        NSArray *tempArr = [WXLSongsModel modelHandelWithArray:responseObject[@"data"][@"songs"]];
        
        if (tempArr.count) {
            for (WXLSongsModel *model in tempArr) {
                [self.songsArr addObject:model];
            }
        }
        
        [_tableView reloadData];
        
    } filed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

// 点击按钮刷新
- (void)refreshDataHandelFromUrl {
    
    NSString *urlStr = [NSString stringWithFormat:@"http://api.favorite.ttpod.com/favorite/song/plaza?address=辽宁省大连市沙河口区五一路314&agent=none&longitude=0.0&utdid=VGGJcU4veJsDACPAEYL62k1V&net=2&from=android&os=6.0.1&v=v8.4.0.2016022715&alf=700159&api_version=%ld.0&imei=863360026086235&version=405144&latitude=0.0&f=168&resolution=1080x1920&language=zh&random=1&user_id=0", _page];
    [WxlAPPTools GETWithURL:urlStr par:nil success:^(id responseObject) {
        
        if (_songsArr.count) {
            [self.songsArr removeAllObjects];
        }
        
        NSArray *tempArr = [WXLSongsModel modelHandelWithArray:responseObject[@"data"][@"songs"]];
        
        if (tempArr.count) {
            for (WXLSongsModel *model in tempArr) {
                [self.songsArr addObject:model];
            }
        }
        
        [_tableView reloadData];
        
    } filed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}



#pragma mark - 轻扫
- (void)swipeAction:(UISwipeGestureRecognizer *)swipe {
    
    [self presentViewController:[WXLPlayMusicViewController shareWXLPlayMusicViewController] animated:YES completion:nil];
}


#pragma mark - 点击
- (void)leftReturnItemAction:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - button点击方法
- (void)playButtonButtonAction:(UIButton *)button {
    if (_page < 0) {
        [self dataHandelFromUrl];
    } else {
        _page--;
        [self refreshDataHandelFromUrl];
    }
    
    
}

- (void)refreshButtonAction:(UIButton *)button {
    [self refreshDataHandelFromUrl];
    _page++;
}

- (void)buttonAction:(UIButton *)button {

    if ([button.titleLabel.text isEqualToString:@"播"]) {
        
        if (_isPlay == YES) {
            [PLAYMUSIC pausePlay];
        } else {
            [PLAYMUSIC startPlay];
        }
        _isPlay = !_isPlay;
    }
}





// 取消 黑色
- (void)cancelBlackLine {
    // 取消navigationbar下面的一条素的黑线
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        NSArray *list = self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView = (UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2 = (UIImageView *)obj2;
                        imageView2.hidden = YES;
                    }
                }
            }
        }
    }
}


#pragma mark - scrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // tableView滑动时，图片的放大缩小
    CGFloat yOffset = scrollView.contentOffset.y;
    CGFloat xOffset = (yOffset + GroupHeight) * 2;
    if (yOffset < -GroupHeight) {
        CGRect rect = _imagView.frame;
        rect.origin.y = yOffset;
        rect.size.height = -yOffset;
        rect.origin.x = xOffset;
        rect.size.width = self.view.frame.size.width + fabs(xOffset) * 2;
        
        _imagView.frame = rect;
    }
//    CGFloat alpha = (yOffset + GroupHeight) / GroupHeight + 0;
    
    UIColor *color = [UIColor colorWithRed:0.42 green:0.33 blue:0.28 alpha:0];
    // 实现navigationBar的滑动隐藏
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[color colorWithAlphaComponent:0]] forBarMetrics:UIBarMetricsDefault];
}


- (UIImage *)imageWithColor:(UIColor *)color {
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文获取图片
    UIImage *theImag = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    return theImag;
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.translucent = YES;
    
    // 保证安全
    if (!self.animation) {
        self.animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    }
    // 旋转的起始值
    _animation.fromValue = [NSNumber numberWithFloat:0];
    // 旋转的结束值
    // π 是 180°  2π 是 360°
    _animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    // 重复次数
    _animation.repeatCount = NSIntegerMax;
    // 时间
    _animation.duration = 5;
    // 是否自动回到原来位置
    _animation.autoreverses = NO;
    // 是否按照结束位置继续旋转
    _animation.cumulative = YES;
    
    [_imgView.layer addAnimation:_animation forKey:@"标记"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.translucent = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
